/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lmx.repoDomain.repository;

import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.annotations.JsonApiFindAll;
import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.AccountService;
import com.lmx.persistence.service.CustomerBusinessFlowService;
import com.lmx.persistence.service.CustomerService;
import com.lmx.persistence.service.TimerService;
import com.lmx.persistence.service.WorkPlaceService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.Customer;
import com.lmx.repoDomain.tmodel.CustomerBill;
import com.lmx.repoDomain.tmodel.CustomerBusinessFlow;
import com.lmx.repoDomain.tmodel.Dicttype;

@JsonApiResourceRepository(CustomerBusinessFlow.class)
@Component
public class CustomerBusinessFlowRepository extends BaseRepository<CustomerBusinessFlow> {

	@Autowired
	private CustomerService customerService;

	@Autowired
	private AccountService accountService;

	@Autowired
	private WorkPlaceService workPlaceService;
	@Autowired
	private TimerService timerService;
	@Autowired
	private CustomerBusinessFlowService customerBusinessFlowService;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(CustomerBusinessFlow.class);
	}

	@Override
	@JsonApiSave
	public CustomerBusinessFlow save(CustomerBusinessFlow record) {
		int operateFlag = 1;
		// StatThreadService statThread = new StatThreadService();
		Long tenantId = ActionContextHolder.getContext().getTenantId();
		int count = customerBusinessFlowService.findCountCustomerBusinessFlow(tenantId);
		if (null == record.getInContractNO()) {// 传入合同号
			record.setInContractNO(CommonUtil.getContractNO(count + 1));
		}
		if (record.getId() == null) {
			// 新建预定将预定状态置为预定
			if (record.getStatus() != null
					&& ("consultStatus3".equals(record.getStatus().getTypecode()))) {
				record.setOrderStatus(commonService.getDicttype("orderStatus1"));
			}
			// 申请退住
			if (record.getLeaveStatus() != null
					&& CommonConstants.DICTTYPE.FLOW_LEAVE_STATUS_1.label().equals(
							record.getLeaveStatus().getTypecode())) {
				// 将原有flow状态改为已提交退住
				// customerService.updateBusinessFlowStatusByCustomer(record.getCustomer(),"");

			} else {
				// 预定 直接试住 入住 修改床位状态 客户状态 产生 变更记录
				operateFlag = customerService.operateBusinessFlowFlag(record);// 验证床位是否可用
				if (operateFlag == 0) {
					record.setErrcode(9);// 床位已占用
					throw new BusinessException(null, CommonConstants.ERROR_CODE.BED_USED.label(),
							null);
				}
				List<Customer> dataC = customerService.getCustomerByCardCode(record
						.getCustomerCardCode());
				if (dataC != null && dataC.size() > 0) {
					record.setErrcode(3);// 身份证重复
					throw new BusinessException(null,
							CommonConstants.ERROR_CODE.CARDCODE_ERROR.label(), null);
				}
				/*
				 * List<Customer> dataN =
				 * customerService.getCustomerByContractNO(record
				 * .getInContractNO()); if (dataN != null && dataN.size() > 0) {
				 * record.setErrcode(7);// 合同重复 throw new
				 * BusinessException(null,
				 * CommonConstants.ERROR_CODE.CONTRACTNO_ERROR.label(), null); }
				 */
				record = customerService.directCreateBusinessFlow(record);
//				timerService.statConsultQuery();
//				timerService.statInTryBackQuery();
				return record;
			}
			dslJpaService.create(record);
		} else {
			if (record.getDelStatus() == 1) {// 删除

			} else {
				// 验证合同编号 to do
				CustomerBusinessFlow ctTemp = customerService.getCustomerBusinessFlow(record);
				// 预定取消
				if (record.getStatus() != null
						&& ("consultStatus3".equals(record.getStatus().getTypecode()))
						&& (ctTemp.getOrderStatus() == null || "orderStatus1".equals(ctTemp
								.getOrderStatus().getTypecode()))
						&& "orderStatusQX".equals(record.getOrderStatus().getTypecode())) {
					customerService.deleteCustomerOnOperateFLow(record.getCustomer());
				}
				// 入住状态发生改变 更改客户状态 床位状态 生成服务变更记录 预定-试住 预定--入住 试住--入住
				if (ctTemp.getStatus() != null && record.getStatus() != null
						&& record.getBackRemark() != null && "in".equals(record.getBackRemark())) {
					if (!ctTemp.getStatus().getTypecode().equals(record.getStatus().getTypecode())) {
						operateFlag = customerService.operateBusinessFlowFlag(record);// 验证床位是否可用
						if (operateFlag == 0) {
							record.setErrcode(9);// 床位已占用
							throw new BusinessException(null,
									CommonConstants.ERROR_CODE.BED_USED.label(), null);
						}
						List<Customer> dataN = customerService.getCustomerByContractNOFilterId(
								record.getInContractNO(), record.getCustomer().getId());
						if (dataN != null && dataN.size() > 0) {
							record.setErrcode(7);// 合同重复
							throw new BusinessException(null,
									CommonConstants.ERROR_CODE.CONTRACTNO_ERROR.label(), null);
						}
						customerService.businessFlowStatusChanged(ctTemp, record);
					}
				}

				// 退住(leaveStatus: 费用结算完成-->完成退住)
				if (ctTemp.getLeaveStatus() != null
						&& CommonConstants.DICTTYPE.FLOW_LEAVE_STATUS_4.label().equals(
								ctTemp.getLeaveStatus().getTypecode())
						&& record.getLeaveStatus() != null
						&& CommonConstants.DICTTYPE.FLOW_LEAVE_STATUS_3.label().equals(
								record.getLeaveStatus().getTypecode())) {
					record = customerService.operateCustomerBack(record);
//					timerService.statConsultQuery();
//					timerService.statInTryBackQuery();
					return record;
				}

				// 退住(leaveStatus:申请退住-->审核通过)如果为当天之前（包括当天）退住 生成当月账单
				if (ctTemp.getLeaveStatus() != null
						&& CommonConstants.DICTTYPE.FLOW_LEAVE_STATUS_1.label().equals(
								ctTemp.getLeaveStatus().getTypecode())
						&& record.getLeaveStatus() != null
						&& CommonConstants.DICTTYPE.FLOW_LEAVE_STATUS_4.label().equals(
								record.getLeaveStatus().getTypecode())) {
					Integer yesTimeStart = null;
					Integer yesTimeEnd = null;
					String dayTime = "";// 当天日期
					try {
						dayTime = CommonUtil.getCurrTimeForString();// 当天日期
						yesTimeStart = CommonUtil.strToIntegerTime(dayTime.substring(0, 10)
								+ " 00:00:00");
						yesTimeEnd = CommonUtil.strToIntegerTime(dayTime.substring(0, 10)
								+ " 23:59:59");
					} catch (Exception e) {
						e.printStackTrace();
					}
					// 退住日期 今天之前（包括今天）
					if (record.getLeaveDate() <= yesTimeEnd) {
						record = customerService.operateCustomerBackOnDay(record,
								record.getCustomer(), 0, new HashMap<>());
//						timerService.statConsultQuery();
//						timerService.statInTryBackQuery();
						return record;
					}
				}
			}
			dslJpaService.update(record);
		}
//		timerService.statConsultQuery();
//		timerService.statInTryBackQuery();
		return record;
	}

	@Override
	@JsonApiFindAll
	public Iterable<CustomerBusinessFlow> findAll(final QueryParams requestParams) {
		List<CustomerBusinessFlow> datas = new ArrayList();
		datas = (List) super.findAll(requestParams);
		// 对于退住flow信息 设置账单状态 用checkInRemark 存放相应订单状态 done 账单结算完成 none 账单未出
		// created账单已出
		if (datas != null && datas.size() > 0) {
			Map<Long, Dicttype> flowMap = new HashMap<>();
			List<CustomerBill> bills = accountService.findCustomerBillOnFlow(datas);
			// Map<CustomerBusinessFlow, Dicttype> flowMap =
			// (Map<CustomerBusinessFlow, Dicttype>) bills.stream().collect(
			// Collectors.toMap(CustomerBill::getFlow,
			// CustomerBill::getBillStatus, (key1, key2) -> key2));
			if (bills != null && bills.size() > 0) {
				for (CustomerBill bill : bills) {
					flowMap.put(bill.getFlow().getId(), bill.getBillStatus());
				}
			}
			for (CustomerBusinessFlow flow : datas) {
				if (flowMap.containsKey(flow.getId())) {
					// 审核通过
					if (CommonConstants.DICTTYPE.BILL_STATUS_2.label().equals(
							flowMap.get(flow.getId()).getTypecode())) {
						flow.setCheckInRemark("done");// 账单结算完成
					} else {
						flow.setCheckInRemark("created");// 账单已出
					}
				} else {
					flow.setCheckInRemark("none");// 账单未出
				}
			}
		}
		return datas;
	}

}
